Rem
	Based on the "Indiepath.Render2Texture" source code.
	Changes include...
	 * OpenGL only. 
	 * Inline source code (not a module).
	 * Type and Function Renaming.
End Rem

Type GFX_TextureRender
	
	Global GLFrame:TGLImageFrame
	Global Image:TImage = CreateImage(1,1)
	Global Width:Int
	Global Height:Int
			
	Function Create:TImage(Width:Int,Height:Int,Flags:Int=MIPMAPPEDIMAGE|FILTEREDIMAGE)
		Local t:TImage = New TImage
		t.width        = width
		t.height       = height
		t.flags        = flags
		t.mask_r       = 0
		t.mask_g       = 0
		t.mask_b       = 0
		t.pixmaps      = New TPixmap[1]
		t.frames       = New TImageFrame[1]
		t.seqs         = New Int[1]
		t.pixmaps[0]   = t.Lock(0,True,False)
		t.seqs[0]      = GraphicsSeq
		If t.flags & MIPMAPPEDIMAGE Then
			' Fix MAPMAPPED white texture issue...
			t.frames[0] = TGLImageFrame.CreateFromPixmap:TGLImageFrame( t.pixmaps[0],t.flags ~ MIPMAPPEDIMAGE)
			gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA8, width, height, GL_RGBA, GL_UNSIGNED_BYTE, t.pixmaps[0]);
		Else
			t.frames[0] = TGLImageFrame.CreateFromPixmap:TGLImageFrame( t.pixmaps[0],t.flags)		
		End If
		Return t
	End Function

	Function SetViewport(X:Int=0,Y:Int=0,Width:Int=640,Height:Int=480,FlipY:Byte=False)
		If FlipY
			glViewport(X, Y, Width, Height)
			glMatrixMode(GL_PROJECTION)
			glPushMatrix()
			glLoadIdentity()
			gluOrtho2D(X, Width, Height,Y)
			glScalef(1, -1, 1)
			glTranslatef(0, -Height, 0)
			glMatrixMode(GL_MODELVIEW)
		Else
			glViewport(X, Y, Width, Height)
			glMatrixMode(GL_PROJECTION)
			glLoadIdentity()
			glOrtho(X, Width, Height, Y, -1, 1)
			glMatrixMode(GL_MODELVIEW)
			glLoadIdentity()
		EndIf
	EndFunction

	Function Cls(r:Int = 0, g:Int = 0, b:Int = 0, a:Float = 0)
		glClearColor r/255.0, g/255.0 ,b/255.0, a
		glClear GL_COLOR_BUFFER_BIT
	End Function
	
	Function BeginTexture(Image1:TImage,Viewport:Byte=True)
		Image = Image1
		If Viewport Then 
			Width  = image1.width
			Height = image1.height
			GFX_TextureRender.SetViewport(0,0,Width,Height,True)
		Else
			Width  = GraphicsWidth()
			Height = GraphicsHeight()
		EndIf		
		GLFrame:TGLImageFrame = TGLImageFrame(Image1.frame(0))
	End Function
	
	Function EndTexture()
		glBindTexture GL_TEXTURE_2D,GLFrame.name
		glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, Width, Height, 0)
		glBindTexture GL_TEXTURE_2D,0
		GFX_TextureRender.SetViewport(0,0,GraphicsWidth(),GraphicsHeight())
	End Function
	
	Function BeginBackBuffer()
		GFX_TextureRender.SetViewport(0,0,GraphicsWidth(),GraphicsHeight())
	End Function
	
	Function EndBackBuffer()
		glBindTexture GL_TEXTURE_2D,0
	End Function
	
End Type
